<script setup lang="ts">
import { ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { useDesign } from '@/hooks/web/useDesign'
import LockDialog from './components/LockDialog.vue'
import { ref, computed, watch } from 'vue'
import LockPage from './components/LockPage.vue'
import { useLockStore } from '@/store/modules/lock'
import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
import { useTagsView } from '@/hooks/web/useTagsView'
import { useRouter, RouteRecordRaw, RouteLocationNormalizedLoaded } from 'vue-router'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { getTestRoleApi, getAdminRoleApi } from '@/api/login'
import { useForm } from '@/hooks/web/useForm'

const { formMethods } = useForm()
// const { getFormData } = formMethods

const { currentRoute, addRoute, push } = useRouter()

const userStore = useUserStore()

const lockStore = useLockStore()

const permissionStore = usePermissionStore()

const tagsViewStore = useTagsViewStore()

const getIsLock = computed(() => lockStore.getLockInfo?.isLock ?? false)

const { getPrefixCls } = useDesign()

const prefixCls = getPrefixCls('user-info')

const { t } = useI18n()

const redirect = ref<string>('')
watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)

const loginOut = () => {
  userStore.logoutConfirm()
}

const dialogVisible = ref<boolean>(false)

// 锁定屏幕
const lockScreen = () => {
  dialogVisible.value = true
}

const toDocument = () => {
  window.open('https://element-plus-admin-doc.cn/')
}

const toPage = (path: string) => {
  push(path)
}

// 切换系统
/**
 * systemType: string 系统类型，默认为前台系统 后台系统isAdmin
 */
const isAdmin = ref<boolean>(userStore.getIsSys)

const { closeAll } = useTagsView()
const checkSystem = () => {
  isAdmin.value = !isAdmin.value
  userStore.setIsSys(isAdmin.value)
  getRole()
}

// 获取角色信息
const getRole = async () => {
  // 模拟前后台系统获取不同数据 （目前是调用不同接口）
  const params = {
    roleName: isAdmin.value ? 'test' : 'admin'
  }
  const res = isAdmin.value ? await getTestRoleApi(params) : await getAdminRoleApi(params)
  if (res) {
    const routers = res.data || []
    permissionStore.clearAddRouters()
    userStore.setRoleRouters(routers)
    await permissionStore.generateRoutes(routers).catch(() => {})
    permissionStore.getAddRouters.forEach((route) => {
      addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
    })
    permissionStore.setIsAddRouters(true)
    // 关闭所有标签 进入新页面
    tagsViewStore.clearTags()
    closeAll(() => {
      push({ path: redirect.value || permissionStore.addRouters[0].path })
    })
  }
}
</script>

<template>
  <ElDropdown class="custom-hover" :class="prefixCls" trigger="click">
    <div class="flex items-center">
      <img
        src="@/assets/imgs/avatar.jpg"
        alt=""
        class="w-[calc(var(--logo-height)-25px)] rounded-[50%]"
      />
      <span class="<lg:hidden text-14px pl-[5px] text-[var(--top-header-text-color)]">{{
        userStore.getUserInfo?.username
      }}</span>
    </div>
    <template #dropdown>
      <ElDropdownMenu>
        <ElDropdownItem>
          <div @click="toPage('/personal/personal-center')">
            {{ t('router.personalCenter') }}
          </div>
        </ElDropdownItem>
        <ElDropdownItem>
          <div @click="checkSystem()"> {{ isAdmin ? '业务平台' : '后台系统' }} </div>
        </ElDropdownItem>
        <ElDropdownItem>
          <div @click="toDocument">{{ t('common.document') }}</div>
        </ElDropdownItem>
        <ElDropdownItem divided>
          <div @click="lockScreen">{{ t('lock.lockScreen') }}</div>
        </ElDropdownItem>
        <ElDropdownItem>
          <div @click="loginOut">{{ t('common.loginOut') }}</div>
        </ElDropdownItem>
      </ElDropdownMenu>
    </template>
  </ElDropdown>

  <LockDialog v-if="dialogVisible" v-model="dialogVisible" />
  <teleport to="body">
    <transition name="fade-bottom" mode="out-in">
      <LockPage v-if="getIsLock" />
    </transition>
  </teleport>
</template>

<style scoped lang="less">
.fade-bottom-enter-active,
.fade-bottom-leave-active {
  transition:
    opacity 0.25s,
    transform 0.3s;
}

.fade-bottom-enter-from {
  opacity: 0;
  transform: translateY(-10%);
}

.fade-bottom-leave-to {
  opacity: 0;
  transform: translateY(10%);
}
</style>
